package main

import (
	"database/sql"
	"fmt"
	"log"
	"sync"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	var startId int64 = 3000
	var wg sync.WaitGroup
	ch := make(chan struct{}, 1024)
	// lotteryId := 232
	for i := 0; i < 300; i++ {
		wg.Add(1)
		ch <- struct{}{}
		go func() {
			defer wg.Done()
			Trans(startId + int64(i))
			<-ch
		}()
	}
	wg.Wait()
}

func Trans(id int64) {
	// 数据库连接字符串
	dsn := "root:PXDN93VRKUm8TeE7@tcp(192.168.0.108:33069)/looklook_usercenter?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// 开始一个事务
	tx, err := db.Begin()
	if err != nil {
		log.Fatal(err)
	}

	// 定义查询和更新的变量
	var createTime, updateTime, deleteTime sql.NullTime
	var delState, version int64
	var password, nickname, avatar, info string
	var sex, isAdmin int64
	var signature, locationName string
	var longitude, latitude float64
	var totalPrize, fans, allLottery, initiationRecord, winningRecord int64

	mobile := "12345678901"
	newNickname := "New Nickname"

	// 执行 SELECT 操作
	err = tx.QueryRow(`
		SELECT id, create_time, update_time, delete_time, del_state, version, password, 
		nickname, sex, avatar, info, is_admin, signature, location_name, longitude, 
		latitude, total_prize, fans, all_lottery, initiation_record, winning_record 
		FROM user WHERE id = ?`, id).Scan(
		&id, &createTime, &updateTime, &deleteTime, &delState, &version, &password,
		&nickname, &sex, &avatar, &info, &isAdmin, &signature, &locationName, &longitude,
		&latitude, &totalPrize, &fans, &allLottery, &initiationRecord, &winningRecord)

	if err != nil {
		tx.Rollback() // 回滚事务
		log.Fatal(err)
	}

	// 输出 SELECT 结果
	// fmt.Printf("User before update: %+v\n", map[string]interface{}{
	// 	"id":                id,
	// 	"create_time":       createTime,
	// 	"update_time":       updateTime,
	// 	"delete_time":       deleteTime,
	// 	"del_state":         delState,
	// 	"version":           version,
	// 	"password":          password,
	// 	"nickname":          nickname,
	// 	"sex":               sex,
	// 	"avatar":            avatar,
	// 	"info":              info,
	// 	"is_admin":          isAdmin,
	// 	"signature":         signature,
	// 	"location_name":     locationName,
	// 	"longitude":         longitude,
	// 	"latitude":          latitude,
	// 	"total_prize":       totalPrize,
	// 	"fans":              fans,
	// 	"all_lottery":       allLottery,
	// 	"initiation_record": initiationRecord,
	// 	"winning_record":    winningRecord,
	// })

	// 执行 UPDATE 操作
	_, err = tx.Exec(`
		UPDATE user SET nickname = ? WHERE mobile = ?`, newNickname, mobile)
	if err != nil {
		tx.Rollback() // 回滚事务
		log.Fatal(err)
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("User %v updated successfully\n", id)
}
